<template>
  <view>
    <u-sticky>
      <u-navbar back-text=" " title="材料收货" :background="background" title-color="#ffffff" :custom-back="customBack" back-icon-color="#ffffff" ref="navbar" title-size="36"></u-navbar>
      <xmInfo
        :projectno="itemContent.projectno"
        :projectname="itemContent.projectname"
        ref="xmInfo"
      ></xmInfo>
	  <u-tabs
	    :list="isReadList"
	    :is-scroll="false"
	    :current="current"
	    @change="change"
	    active-color="#aaaaaa"
	    font-size="26"
	    inactive-color="#666666"
	    bg-color="rgba(62, 151, 176,0.1)"
	    :active-item-style="activeItemStyle"
	  ></u-tabs>
    </u-sticky>

    <view class="cu-card">
      <scroll-view
        scroll-y="true"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :scrolltolower-enabled="true"
        :refresher-triggered="triggered"
        @refresherrefresh="refresherrefresh"
        @scrolltoupper="refresherrefresh"
        :style="{ height: computedScrollViewHeight }"
      >
        <view
          class="scroll-content"
          ref="scrollContent"
          style="
            display: flex;
            flex-direction: column;
            justify-content: space-between;
          "
          :style="{ height: computedScrollViewHeight }"
        >
          <view
            class="cu-item shadow"
            v-for="(item, index) in list"
            :key="index"
          >
			<view v-if="current == 0">
				<view class="cu-form-group" style="display: flex;justify-content: space-between">
				  <view
				    style="
				      display: inline-block;
				      padding: 5px;
				      background: #3e97b0;
				      color: #fff;
				      width: 40px;
				      text-align: center;
				      font-style: italic;
				      font-weight: bold;
				    "
				  >
				    {{ index + 1 }}
				  </view>
				  
				  <view style="flex: 1; margin-left: 10px;">
					<view class="text-xl text-bold">
						{{item.venName || ""}}
					</view>
				  </view>
				</view>
				<view class="cu-form-group" style="display: flex;justify-content: space-between;">
				  <!-- <view class="text-xl text-bold title">单据号</view>
				  <view class="text-xl text-bold" style="flex: 1">{{
				    item.djno || ""
				  }}</view> -->
				  <view class="text-xl text-bold">
				  	{{item.djno || ""}}
				  </view>
				  <view class="text-xl text-bold">
				  	{{ item.ddate || "" }}
				  </view>
				</view>
				
				
				<!-- <view class="cu-form-group">
				  <view class="title">供应商</view>
				  <view style="flex: 1">{{ item.venName || "" }}</view>
				</view> -->
				<!-- <view class="cu-form-group">
				  <view class="title">设计变更单号</view>
				  <view style="flex: 1">{{ item.sno }}</view>
				</view>
				<view class="cu-form-group">
				  <view class="title">供货日期</view>
				  <view style="flex: 1"> {{ formatDate(item.arrDate) || "" }}</view>
				</view> -->
				<view class="cu-form-group">
				  <view class="title">备  注</view>
				  <view style="flex: 1">{{ item.remarks || "" }}</view>
				</view>
				<view
				  class="cu-form-group"
				  style="color: #3e97b0"
				  @click="add(item.id)"
				>
				  <view class="content-footer-right"></view>
				  <view class="">
				  	 确认收货  <u-icon name="arrow-right"></u-icon>
				  </view>
				</view>
			</view>
			
			<view v-else>
				<view class="cu-form-group" style="display: flex;justify-content: space-between">
				  <view
				    style="
				      display: inline-block;
				      padding: 5px;
				      background: #3e97b0;
				      color: #fff;
				      width: 40px;
				      text-align: center;
				      font-style: italic;
				      font-weight: bold;
				    "
				  >
				    {{ index + 1 }}
				  </view>
				  
				 
				  
				  <dictLabel
				    :value="item.status ? item.status : 0"
				    dict-type="bpm_biz_status"
				    :dict-list="dictList"
				    :fontSize="'30rpx'"
				  ></dictLabel>
				</view>
				<view class="cu-form-group" style="display: flex;justify-content: space-between;">
				  <!-- <view class="text-xl text-bold title">单据号</view>
				  <view class="text-xl text-bold" style="flex: 1">{{
				    item.djno || ""
				  }}</view> -->
				  <view class="text-xl text-bold">
				  	{{item.asnno || ""}}
				  </view>
				  <view class="text-xl text-bold">
				  	{{ item.ddate || "" }}
				  </view>
				</view>
				<view class="cu-form-group">
				  <view class="title">供应商</view>
				  <view style="flex: 1">{{ item.venname || "" }}</view>
				</view>
				<!-- <view class="cu-form-group">
				  <view class="title">设计变更单号</view>
				  <view style="flex: 1">{{ item.sno }}</view>
				</view>
				<view class="cu-form-group">
				  <view class="title">供货日期</view>
				  <view style="flex: 1"> {{ formatDate(item.arrDate) || "" }}</view>
				</view> -->
				<view class="cu-form-group">
				  <view class="title">收货人</view>
				  <view style="flex: 1">{{ item.createByName || "" }}</view>
				</view>
				<view class="cu-form-group">
				  <view class="title">备  注</view>
				  <view style="flex: 1">{{ item.remarks || "" }}</view>
				</view>
				
				<!-- <view class="cu-form-group">
				  <view style="flex: 1">{{ item.remarks || "" }}  ({{formatDate(item.arrDate) || "" }}) </view>
				</view> -->
				<view
				  class="cu-form-group"
				  style="color: #3e97b0"
				  
				>
				  <view class="content-footer-right">
					  <view v-if="item.status == '4' || item.status == '5' || item.status == '6'"  @click="handleBpmMyTask({id:item.id})"><u-icon name="checkmark-circle"></u-icon>任务办理</view>
				  </view>
				  <view class="" @click="add(item.id)">
				  	 收货历史  <u-icon name="arrow-right"></u-icon>
				  </view>
				
				</view>
			</view>
			
          </view>
          <u-empty v-if="!list.length" style="height: 100%"></u-empty>
          <view v-if="list.length" class="loadmore">
            <u-loadmore :status="loadStatus"></u-loadmore>
          </view>
        </view>
      </scroll-view>
    </view>
    <view style="height: 80px" ></view>
    <view class="btn-group cu-bar foot">
      <button class="cu-btn  shadow-blur"@click="search">
          <text class="cuIcon-search" style="margin-right: 10px;"> </text> 搜索
      </button>
    </view>
	
	<!-- 组件 dialog -->
	<customDialog
	   ref='dialog'
	  :modalName="modalName"
	  @getModalName="getModalName"
	></customDialog>
  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import dictLabel from "@/pages/zfgs/index/componetns/dictLabel.vue";
import customDialog from "./dialog.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: { xmInfo, dictLabel, customDialog },
  data() {
    return {
      background:{
        backgroundColor: '#3E97B0',
      },
	  dictList: [],
	  isReadList: [
	    {
	      name: "待收货",
	    },
	    {
	      name: "收货历史",
	    },
	  ],
	  current: 0,
	  activeItemStyle: {
	    backgroundColor: "#FAFAFA",
	    color: "#333",
	  },
      list: [],
      itemContent: {},
      query: {
        pageNo: 1,
        pageSize: 20,
        // orderBy: "a.create_date desc",
      },
      loadStatus: "loadmore",
      triggered: false,
      flag: hasPermission('app:btn:add:cailiaoshouhuo'),
      scrollViewHeight: 0,
      headerHeight: 0,
	  modalName: null,
	  modalType: 0,
    };
  },
  onLoad(e) {
    if (typeof e.item !== "undefined") {
      try {
        this.itemContent = JSON.parse(e.item);
        this.query.projectno = this.itemContent.projectno;
        // this.query.projectname = this.itemContent.projectname;
        console.log(this.itemContent);

        this.loadData();
      } catch (error) {
        console.error("Failed to parse item:", error);
      }
    } else {
      console.warn("Item is undefined.");
    }

    this.getDictList();
  },
  mounted() {
    this.$refs.xmInfo.$on('child-mounted-done', () => {
      this.calculateScrollViewHeight();
    });
  },
  computed: {
    computedScrollViewHeight() {
      return this.scrollViewHeight === "auto"
        ? "auto"
        : `${this.scrollViewHeight}px`;
    },
  },
  methods: {
	  handleBpmMyTask(record){
	  	this.$u.api.bpm.bpmTaskDeForm({ formKey: 'flow_asn_shRec', bizKey: record.id }).then((res) => {
	  	  if(res.result == 'true'){
	  		  const url = res.mobileUrl;
	  		  if (url && url != '') {
	  		  	uni.navigateTo({
	  		  		url: url
	  		  	})
	  		  }
	  	  }else{
	  		this.$u.toast(res.message);
	  	  }
	  	});
	  },
	  search() {
	    this.modalName = "DrawerModalR";
		this.$refs.dialog.query=this.query
		// this.modalType = this.current
	    // 隐藏tabbar
	    uni.hideTabBar();
	  },
	  getModalName(item) {
	    console.log(item, "getModalName===");
	    const { modalName, query } = item;
	    this.modalName = modalName;
	    // this.query = query;
		if(this.current == 0){
			this.query.djno = query.djno || ''
			this.query.venName = query.venName || '';
		}else{
			this.query.asnno = query.djno || ''
			this.query.venname = query.venName || '';
		}
	    this.query.pageNo = 1;
	    this.query.pageSize = 20;
	    this.query.projectno = this.itemContent.projectno;
	    // this.query.projectname = this.itemContent.projectname;
	    // if(this.query.projStatus == 0){
	    //   this.current = 0
	    // }else if(this.query.projStatus == 1 || this.query.projStatus == 3 || this.query.projStatus == 4|| this.query.projStatus == 5 || this.query.projStatus == 6 || this.query.projStatus == 7 ){
	    //   this.current = 4
	    // }
	    // console.log(this.query.projStatus ,'this.query.projStatus',this.current)
	    this.loadData();
	  },
	  change(index) {
	    this.current = index;
	    // this.current ? (this.query.pushed = true) : (this.query.pushed = false);
		this.query = {};
	    this.query.pageNo = 1;
		this.query.pageSize = 20;
		this.query.projectno = this.itemContent.projectno;
		// this.query.projectname = this.itemContent.projectname;
	    this.calculateScrollViewHeight();
	    this.loadData();
	  },
    customBack(){
      // 跳转到工作台页面
      // uni.navigateTo({
      //   url: "/pages/zfgs/index/index/index?item=" + JSON.stringify(this.itemContent),
      // });
	  uni.navigateBack({
	    delta: 1,
	  });
    },
    async calculateScrollViewHeight() {
      try {
    // 等待头部高度计算完成
          await new Promise((resolve) => {
            this.$nextTick(() => {
              this.headerHeight = this.$refs.xmInfo.$refs['u-sticky'].height + this.$refs.xmInfo.$refs['u-sticky'].h5NavHeight + this.$refs.navbar.navbarHeight;
              resolve();
            });
          });
          // 计算tabBar高度
          // if(this.flag){
          //   this.tabBarHeight = 80; // 假设tabbar高度为50px，实际应根据实际情况获取
          // }else{
          //   this.tabBarHeight = 0; 
          // }
		  
		  this.tabBarHeight = 80; 

          // 获取屏幕高度
          const systemInfo = uni.getSystemInfoSync();
          const screenHeight = systemInfo.windowHeight;
          console.log('screenHeight',this.headerHeight,this.$refs.xmInfo.$refs['u-sticky']);
          // 计算scroll-view高度
          this.scrollViewHeight = screenHeight - (this.headerHeight + this.tabBarHeight);
      } catch (error) {
        console.error('Error while calculating ScrollView height:', error);
      }
    },
    getDictList() {
      this.$u.api.dictListData({ dictType: "bpm_biz_status" }).then((res) => {
        this.dictList = res;
      });
    },
    // 把年月日时分秒格式化只显示年月日
    formatDate(date) {
		if(date){
			const data = new Date(date);
			const year = data.getFullYear();
			const month = data.getMonth() + 1;
			const day = data.getDate();
			return `${year}-${month}-${day}`;
		}else{
			return '';
		}
		  
    },
    loadMore() {
      this.loadStatus = "loading";
      setTimeout(() => {
        this.query.pageNo += 1;
        this.loadData("add");
      }, 100);
    },
    loadData(type) {
      // 循环10次重复赋值
	  
	  if(this.current == 0){
		  this.$u.api.zfgs.pmAsnShrecListAsnData(this.query).then((res) => {
		    if (res.list.length >= 0) {
		      // this.xmList = res.list
		      if (res.list.length < 20 || res.list.length == 0) {
		        this.loadStatus = "nomore";
		      }
		      var data = res.list;
		      //模拟收藏
		  
		      if (type == "add") {
		        for (var i = 0; i < data.length; i++) {
		          this.list.push(data[i]);
		        }
		      } else {
		        this.list = data;
		      }
		    }
		  });
	  }else{
		  this.$u.api.zfgs.pmAsnShrecListData(this.query).then((res) => {
		    if (res.list.length >= 0) {
		      // this.xmList = res.list
		      if (res.list.length < 20 || res.list.length == 0) {
		        this.loadStatus = "nomore";
		      }
		      var data = res.list;
		      //模拟收藏
		  
		      if (type == "add") {
		        for (var i = 0; i < data.length; i++) {
		          this.list.push(data[i]);
		        }
		      } else {
		        this.list = data;
		      }
		    }
		  });
	  }
     
    },
    async refresherrefresh() {
      this.triggered = true;
      this.query.pageNo = 1;
      await this.loadData();
      const scrollTop = 0;
      uni.pageScrollTo({
        scrollTop,
        duration: 0,
      });
      setTimeout(() => {
        this.triggered = false;
      }, 500);
      // this.triggered = false;
    },
    add(id) {
      if (!!id) {
		  if(this.current == 0){
			  uni.navigateTo({
			    url: "/pages/zfgs/material/receive/pmMaterialneedArr/form?id=" + id,
			    // url: "/pages/zfgs/material/arrival/pmPuArrivalvouch/form?id=" + id,
			  });
			  
			  
		  }else{
			  uni.navigateTo({
			    url: "/pages/zfgs/material/receive/pmAsnShrec/form?id=" + id,
			  });
		  }
        
      } else {
        const xm = {
          projectno: this.itemContent.projectno,
          projectname: this.itemContent.projectname,
        };
        uni.navigateTo({
          url:
            "/pages/zfgs/material/receive/pmMaterialneedArr/form?xm=" +
            JSON.stringify(xm),
        });
      }
    },
  },
  beforeDestroy() {
    // 清理事件监听器
    try {
       this.$refs.xmInfo.$off('child-mounted-done');
     } catch (e) {
       console.log('Error while unbinding event:', e);
     }
  }
};
</script>
<style lang="scss" scoped>
.cu-bar {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  background: #fff;
}
.cu-item {
  flex-wrap: wrap;
  padding: 15px !important;
}
// .line-green{
//   border: 1px solid #39b54a;
//   border-radius: 10rpx;
// }
.title {
  width: 100px;
}
</style>